package com.shenjies88.practice.reactor.hold;

import cn.hutool.core.util.RandomUtil;
import com.shenjies88.practice.reactor.wrapper.WorkWrapper;

import java.nio.channels.SelectionKey;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shenjies88
 * @since 2022/12/7/21:22
 */
public class WorkWrapperHold {

    private static final int WORK_WRAPPER_SIZE = 5;
    private static List<WorkWrapper> workWrapperList = null;

    private WorkWrapperHold() {

    }

    public synchronized static void init() {
        if (workWrapperList != null && workWrapperList.size() > 0) {
            return;
        }
        workWrapperList = new ArrayList<>();
        for (int i = 0; i < WORK_WRAPPER_SIZE; i++) {
            var workWrapper = new WorkWrapper(i);
            workWrapper.init(i);
            workWrapperList.add(workWrapper);
        }
    }

    public static void submit(SelectionKey selectionKey) {
        var index = RandomUtil.randomInt(10, 10000) % WORK_WRAPPER_SIZE;
        var workWrapper = workWrapperList.get(index);
        workWrapper.queue(selectionKey);
    }
}
